1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
//! Library for working with Javascript Promises using Rust code.
//! 
//! This crate contains two main types: `RawPromise`, which is a thin
//! wrapper over JS's promise types, and `Promise`, which helps use
//! promises with Rust types.
//! 
//! All methods that chain a promise currently translate to a `then` call, even if the
//! result is available immediately. So doing as much synchronous work in one `then` call
//! will be slightly more efficient than multiple `then` calls.
//! 
//! In promise callbacks, if a panic or JS error occurs, the library will print the error
//! via `console.error` and return `null` from the promise.
//! 
//! Comparison to stdweb promises
//! -----------------------------
//! 
//! * stdweb promises, at the time of writing, require a feature to access, and are unstable.
//!   This... is also unstable but not locked behind a feature.
//! * stdweb promises try to be compatible with the futures API, which does not map well to
//!   how JS promises and callbacks work. This crate exposes an API that mirrors JS's promises
//!   API.

// Needed for #[async_test]
#![cfg_attr(test, feature(linkage))]

pub mod jsbox;

use stdweb::unstable::TryFrom;
use std::convert::Infallible;
use std::marker::PhantomData;
use std::mem::drop;
use std::panic;
use stdweb::{self, js, console};

use crate::jsbox::*;

/// Wrapper for a JS promise, working with `stdweb::Value`s.
/// 
/// This provides a thin layer over JS promise objects, so that the user does not
/// have to worry about using the `js!{}` macro for calling `then` or ensuring the rust
/// callback functions are freed.
/// 
/// To wrap an existing promise created using `js!{}`, use the `from_reference` or `from_value`
/// functions. You can also use `new_resolved` or `new_rejected` to create pre-resolved promises.
/// 
/// Note that if the promise is never resolved or rejected, it will leak memory, since the
/// rust callbacks will never be freed.
#[derive(Clone)]
pub struct RawPromise {
	p: stdweb::Reference,
}
impl RawPromise {
	/// Wraps an existing promise.
	/// 
	/// This function does not check if the reference points to a valid promise object;
	/// if it doesn't have a `then` method, methods on the wrapper will likely panic.
	pub fn from_reference(p: stdweb::Reference) -> Self {
		Self { p }
	}
	
	/// Wraps an existing promise.
	/// 
	/// Panics if the value is not a reference.
	/// 
	/// This function does not check if the reference points to a valid promise object;
	/// if it doesn't have a `then` method, methods on the wrapper will likely panic.
	pub fn from_value(v: stdweb::Value) -> Self {
		Self { p: v.into_reference().expect("Value passed to RawPromise::from_value was not an object") }
	}
	
	/// Gets the JS reference object to this promise.
	pub fn js_obj(&self) -> &stdweb::Reference {
		&self.p
	}
	
	/// Creates a new promise, already resolved to a value.
	/// 
	/// Calls the JS `Promise.resolve` method.
	pub fn new_resolved(v: stdweb::Value) -> Self {
		let p = js!{ return Promise.resolve(@{v}); };
		Self::from_reference(p.into_reference().expect("Promise.resolve did not return an object"))
	}
	
	/// Creates a new promise, already rejected
	/// 
	/// Calls the JS `Promise.reject` method.
	pub fn new_rejected(v: stdweb::Value) -> Self {
		let p = js!{ return Promise.reject(@{v}); };
		Self::from_reference(p.into_reference().expect("Promise.resolve did not return an object"))
	}
	
	/// Creates a new, already fulfilled promise from a `Result`.
	/// 
	/// Either resolved if the passed-in `Result` is `Ok`, or rejected if
	/// it was `Err`.
	pub fn from_result(v: Result<stdweb::Value, stdweb::Value>) -> Self {
		match v {
			Ok(v) => Self::new_resolved(v),
			Err(v) => Self::new_rejected(v),
		}
	}
	
	/// Runs a function once the promise has resolved.
	/// 
	/// Instead of separate resolve and reject functions, the single callback is passed a
	/// `Result` object. The callback returns a JS value that is interpreted as usual for a
	/// promise return value.
	/// 
	/// Panics
	/// ------
	/// 
	/// If this promise was created by `from_reference` with an invalid promise object
	/// (no `then` method, `then` didn't return an object, etc).
	pub fn then<F: FnOnce(Result<stdweb::Value, stdweb::Value>) -> stdweb::Value + Send + 'static>(&self, f: F) -> Self {
		let invoke_cb = move |v: stdweb::Value, is_ok: bool| {
			let v_res = if is_ok { Ok(v) } else { Err(v) };
			return invoke_tried(|| f(v_res));
		};
		let promise_val = js!{
			let invoke_cb = @{stdweb::Once(invoke_cb)};
			return @{self.js_obj()}.then(function(v) {
				return invoke_cb(v, true);
			}, function(v) {
				return invoke_cb(v, false);
			})
		};
		
		let promise_ref = promise_val.into_reference().expect("promise.then did not return an object");
		Self{p: promise_ref}
	}
	
	/// Runs a function once the promise has resolved, returning Rust objects.
	/// 
	/// This is the main way to switch from JS promises to this crate's typed `Promise` type.
	/// 
	/// Panics
	/// ------
	/// 
	/// If this promise was created by `from_reference` with an invalid promise object
	/// (no `then` method, `then` didn't return an object, etc).
	pub fn then_to_typed<TOk: Send, TErr: Send, F: FnOnce(Result<stdweb::Value, stdweb::Value>) -> PromiseResult<TOk, TErr> + Send + 'static>(&self, f: F) -> Promise<TOk, TErr> {
		let cb = move |v: Result<stdweb::Value, stdweb::Value>| {
			invoke_tried(|| promise_result_to_value(f(v)))
		};
		Promise {
			p: self.then(cb),
			has_consumer: false,
			_ph: Default::default()
		}
	}
	
	/// Creates a new promise that either resolves when all promises passed to it resolve or rejects when at least one
	/// promise passed to it rejects.
	/// 
	/// Binding for JS's `Promise.all` function; see its documentation for semantics.
	pub fn all<I: IntoIterator<Item=RawPromise>>(promises: I) -> RawPromise {
		let promise_objs = promises.into_iter()
			.map(|promise| promise.p)
			.collect::<Vec<_>>();
		let promise_val = js!{
			return Promise.all(@{promise_objs});
		};
		Self::from_value(promise_val)
	}
	
	/// Creates a new promise that resolves when all promises passed to it have resolved or have been rejected.
	/// 
	/// Binding for JS's `Promsie.allSettled` function; see its documentation for semantics.
	pub fn all_settled<I: IntoIterator<Item=RawPromise>>(promises: I) -> RawPromise {
		let promise_objs = promises.into_iter()
			.map(|promise| promise.p)
			.collect::<Vec<_>>();
		let promise_val = js!{
			return Promise.allSettled(@{promise_objs});
		};
		Self::from_value(promise_val)
	}
	
	/// Creates a new promise that waits until the any of the promises passed to it have been resolved or rejected,
	/// returning its result.
	/// 
	/// Binding for JS's `Promsie.race` function; see its documentation for semantics.
	pub fn race<I: IntoIterator<Item=RawPromise>>(promises: I) -> RawPromise {
		let promise_objs = promises.into_iter()
			.map(|promise| promise.p)
			.collect::<Vec<_>>();
		let promise_val = js!{
			return Promise.race(@{promise_objs});
		};
		Self::from_value(promise_val)
	}
}


/// Typed promises, working with Rust types.
/// 
/// This provides a higher level, Rust-like interface for working with Javascript promises.
/// It allows passing Rust values through promises (even if they don't implement `stdweb::JsSerialize`).
/// 
/// Other than the basic functions for creating already-resolved promises, the usual way to create a `Promise`
/// is to create a `RawPromise` object using `js!{}` with a JS API, then use `RawPromise::then_to_typed` to
/// convert the raw JS results to a Rust type (or do something else with it).
/// 
/// If you need to pass the promise to a JS API, you can use `Promise::then_to_raw` to convert the rust objects
/// to JS objects and get a `RawPromise`, which exposes a JS promise object via `js_obj`.
/// 
/// The result types must have only `'static` references, since promises may resolve arbitrairly late, or
/// even not at all.
/// 
/// Note that there are a few limitations of this API due to how the internal passing of Rust objects works:
/// * Chained methods like `then` consume the promise, preventing code from using the promise results multiple
///   times. This is because the result values have to be moved out of the internal box, making them unavailable
///   for other promises. This may be relaxed in the future for types that impement `Clone`.
/// * For the above reason, and to avoid exposing internals that may result in other unsafe behavior, you cannot
///   get the JS promsie object from this type. You can, however, use `then_to_raw` to get a `RawPromise`, which
///   you can get the promise object of.
/// * Like `RawPromise`, if a promise is never resolved, it will leak memory.
pub struct Promise<TOk: Send+'static, TErr: Send+'static> {
	p: RawPromise,
	has_consumer: bool,
	_ph: PhantomData<fn(TOk, TErr)>,
}
impl<TOk: Send+'static, TErr: Send+'static> Promise<TOk, TErr> {
	/// Runs a function once the promise has resolved.
	/// 
	/// The callback is passed a `Result`, which is `Ok` if the promise was resolved or `Err` if rejected.
	/// It returns a `PromiseResult`, which can contain an immediate value to resolve to, another promise to run,
	/// or an error to reject the promise with.
	pub fn then<TNewOk: Send+'static, TNewErr: Send+'static, F: FnOnce(Result<TOk, TErr>) -> PromiseResult<TNewOk, TNewErr> + Send + 'static>(mut self, f: F) -> Promise<TNewOk, TNewErr> {
		let cb = move |res: Result<stdweb::Value, stdweb::Value>| {
			let unboxed_res = match res {
				Ok(raw_v) => {
					if raw_v == stdweb::Value::Null {
						// Likely that previous promise threw an error and returned null.
						return stdweb::Value::Null;
					}
					
					let unboxed_maybe = unsafe { js_unbox::<TOk>(raw_v.clone()) };
					let unboxed = match unboxed_maybe {
						Some(v) => v,
						None => {
							console!(error, "Could not unbox rust value from promise result. This is probably a bug with the js-promises crate. Value:", raw_v);
							return stdweb::Value::Null;
						}
					};
					Ok(unboxed)
				},
				Err(raw_v) => {
					if raw_v == stdweb::Value::Null {
						// Likely that previous promise threw an error and returned null.
						return stdweb::Value::Null;
					}
					
					let unboxed_maybe = unsafe { js_unbox::<TErr>(raw_v.clone()) };
					let unboxed = match unboxed_maybe {
						Some(v) => v,
						None => {
							console!(error, "Could not unbox rust value from promise result. This is probably a bug with the js-promises crate. Value:", raw_v);
							return stdweb::Value::Null;
						}
					};
					Err(unboxed)
				},
			};
			
			return invoke_tried(|| promise_result_to_value(f(unboxed_res)));
		};
		self.has_consumer = true;
		Promise {
			p: self.p.then(cb),
			has_consumer: false,
			_ph: Default::default(),
		}
	}
	
	/// Creates a new promise, already resolved to a value
	pub fn new_resolved(v: TOk) -> Self {
		Self {
			p: RawPromise::new_resolved(js_box(v)),
			has_consumer: false,
			_ph: Default::default(),
		}
	}
	
	/// Creates a new promise, already rejected
	pub fn new_rejected(v: TErr) -> Self {
		Self {
			p: RawPromise::new_rejected(js_box(v)),
			has_consumer: false,
			_ph: Default::default(),
		}
	}
	
	/// Creates a new, already fulfilled promise from a `Result`.
	/// 
	/// Either resolved if the passed-in `Result` is `Ok`, or rejected if
	/// it was `Err`.
	pub fn from_result(v: Result<TOk, TErr>) -> Self {
		match v {
			Ok(v) => Self::new_resolved(v),
			Err(v) => Self::new_rejected(v),
		}
	}
	
	
	/// Runs a function once the promise has resolved, returning JS objects.
	/// 
	/// Use this to convert a typed promise into a raw promise, that can be passed
	/// to JS code.
	pub fn then_to_raw<F: FnOnce(Result<TOk, TErr>) -> stdweb::Value + Send + 'static>(mut self, f: F) -> RawPromise {
		let cb = move |v: Result<stdweb::Value, stdweb::Value>| {
			let unboxed_res = match v {
				Ok(v) => unsafe { Ok(js_unbox::<TOk>(v).expect("Promise::then got invalid box to cb")) },
				Err(v) => unsafe { Err(js_unbox::<TErr>(v).expect("Promise::then got invalid box to cb")) },
			};
			return (f)(unboxed_res);
		};
		self.has_consumer = true;
		self.p.then(cb)
	}
	
	/// Runs an operations on the resolve value if the promise resolves successfully.
	/// 
	/// Leaves rejected promises alone.
	pub fn map<TNewOk: Send+'static, F: FnOnce(TOk) -> TNewOk + Send + 'static>(self, f: F) -> Promise<TNewOk, TErr> {
		self.then(move |v: Result<TOk, TErr>| v.map(f).map(|v| v.into()))
	}
	
	/// Runs an operation on the reject value if the promise is rejected.
	/// 
	/// Leaves resolved promises alone.
	pub fn map_err<TNewErr: Send+'static, F: FnOnce(TErr) -> TNewErr + Send + 'static>(self, f: F) -> Promise<TOk, TNewErr> {
		self.then(move |v: Result<TOk, TErr>| v.map_err(f).map(|v| v.into()))
	}
	
	/// Runs an operation on the resolve value if the promise resolves successfully, possibly failing or returning another promise.
	/// 
	/// Leaves rejected promises alone, forwarding the error object.
	pub fn and_then<TNewOk: Send+'static, F: FnOnce(TOk) -> PromiseResult<TNewOk, TErr> + Send + 'static>(self, f: F) -> Promise<TNewOk, TErr> {
		self.then(move |v: Result<TOk, TErr>| {
			let v = match v {
				Ok(v) => v,
				Err(err) => { return Err(err).into(); },
			};
			(f)(v)
		})
	}
	
	/// Creates a promise that resolves when all of the passed-in promises have been resolved or rejected.
	/// 
	/// Resolves to a `Vec` of results for each of the promises. Never rejected.
	/// 
	/// This is currently the only promise combinator for typed `Promise`s, due to memory leak issues
	/// with the other functions.
	pub fn all_settled<I: IntoIterator<Item=Self>>(promises: I) -> Promise<Vec<Result<TOk, TErr>>, Infallible> {
		let promise_objs = promises.into_iter()
			.map(|mut promise| {
				promise.has_consumer = true;
				promise.p.js_obj().clone()
			})
			.collect::<Vec<_>>();
		
		RawPromise::from_value(js!{
			return Promise.allSettled(@{promise_objs});
		}).then_to_typed(|res| {
			let array = stdweb::Array::try_from(
				res
				.expect("Promise from Promise.allSettled was rejected")
				.into_reference()
				.expect("Value from Promise.allSettled was not a reference")
			).expect("Value from Promise.allSettled was not an array");
			
			let value_vec = Vec::from(array);
			
			Ok(value_vec.into_iter()
				.map(|val| {
					let status_val = js!{ return @{val.clone()}.status; };
					let status = status_val.as_str().expect("Promise.allSettled entry.status was not a string");
					match status {
						"fulfilled" => {
							let v = js!{ return @{val}.value; };
							unsafe { Ok(js_unbox::<TOk>(v).expect("Promise.allSettled got invalid box to cb")) }
						},
						"rejected" => unsafe {
							let v = js!{ return @{val}.reason; };
							Err(js_unbox::<TErr>(v).expect("Promise.allSettled got invalid box to cb"))
						},
						_ => { panic!("Promise.allSettled entry.status was not 'fulfilled' or 'rejected', was {:?}", status); }
					}
				})
				.collect::<Vec<_>>()
				.into()
			)
		})
	}
}
impl<TOk: Send, TErr: Send> Drop for Promise<TOk, TErr> {
	fn drop(&mut self) {
		// If nothing is receiving the value from this promise, set up a callback to release the unused
		// results to prevent leaking memory.
		if self.has_consumer {
			return;
		}
		self.p.then(|v: Result<stdweb::Value, stdweb::Value>| {
			match v {
				Ok(v) => drop(unsafe { js_unbox::<TOk>(v) }),
				Err(v) => drop(unsafe { js_unbox::<TErr>(v) }),
			}
			return stdweb::Value::Null;
		});
	}
}

/// Return type for `Promise.then`, which can be an immediate value to resolve to,
/// another promise to run, or an immediate value to reject.
/// 
/// Similar in usage to `futures::Poll`.
pub type PromiseResult<TOk, TErr> = Result<PromiseOk<TOk, TErr>, TErr>;

/// A non-error result from a promise; can be either an immediate Ok value, or another promise to execute.
/// 
/// Similar in usage to `futures::Async`, though returns a promise to exeute instead of
/// a simple `NotReady` value.
pub enum PromiseOk<TOk: Send+'static, TErr: Send+'static> {
	Immediate(TOk),
	Promise(Promise<TOk, TErr>),
}
impl<TOk: Send, TErr: Send> From<TOk> for PromiseOk<TOk, TErr> {
	fn from(v: TOk) -> Self {
		Self::Immediate(v)
	}
}
impl<TOk: Send, TErr: Send> From<Promise<TOk, TErr>> for PromiseOk<TOk, TErr> {
	fn from(v: Promise<TOk, TErr>) -> Self {
		Self::Promise(v)
	}
}

/// Converts a `PromiseResult` to a JS value, boxing immediate values.
fn promise_result_to_value<TOk: Send, TErr: Send>(v: PromiseResult<TOk, TErr>) -> stdweb::Value {
	match v {
		Ok(PromiseOk::Immediate(v)) => js!{ return Promise.resolve(@{js_box(v)}) },
		Ok(PromiseOk::Promise(mut p)) => {
			p.has_consumer = true;
			p.p.js_obj().into()
		},
		Err(v) => js!{ return Promise.reject(@{js_box(v)}) },
	}
}

fn invoke_tried<F: FnOnce() -> stdweb::Value + 'static>(f: F) -> stdweb::Value {
	// Dumb panic handling.
	// Don't want to just reject the promise, because a) that doesn't really match normal panic behavior,
	// and b) could throw an error with an invalid box, breaking safety.
	return js!{
		try {
			return @{stdweb::Once(f)}();
		} catch(e) {
			console.error("Rust future callback panicked or threw JS error:", e);
			return null;
		}
	};
}

#[cfg(test)]
mod tests {
	use super::*;
	use serde_json;
	use std::fmt::Display;
	use std::string::ToString;
	use stdweb::async_test;
	use stdweb::console;
	
	fn test_promise<TOk: Send, TErr: Send, FDone>(p: Promise<TOk, TErr>, done: FDone)
	where
		TErr: Display,
		FDone: FnOnce(Result<(), String>) + Send + 'static,
	{
		p.then_to_raw(move |res| {
			let res = res
				.map(|_| ())
				.map_err(|e| format!("Promise rejected: {}", e));
			done(res);
			return stdweb::Value::Null;
		});
	}
	
	fn test_raw_promise<FDone>(p: RawPromise, done: FDone)
	where
		FDone: FnOnce(Result<(), String>) + Send + 'static,
	{
		p.then(move |res| {
			let res = res
				.map(|_| ())
				.map_err(|e| format!("Promise rejected with value {}", js_to_string(e)));
			done(res);
			return stdweb::Value::Null;
		});
	}
	
	fn reject_raw<Why: ToString>(why: Why) -> stdweb::Value {
		return js!{ return Promise.reject(@{why.to_string()}); };
	}
	
	fn js_to_string(v: stdweb::Value) -> String {
		return js!{ return JSON.stringify(@{v}); }.into_string().unwrap();
	}
	
	#[async_test]
	fn raw_promise_new_resolved<F: FnOnce(Result<(), String>)>(done: F) {
		let p = RawPromise::new_resolved(123u32.into())
			.then(|res| {
				let value = match res {
					Ok(v) => v,
					Err(_) => {
						return reject_raw("new_resolved was rejected");
					}
				};
				if value != stdweb::Value::Number(123u32.into()) {
					return reject_raw(format!("new_resolved expected 123, got {}", js_to_string(value)));
				}
				return stdweb::Value::Null;
			});
		test_raw_promise(p, done);
	}
	
	#[async_test]
	fn raw_promise_new_rejected<F: FnOnce(Result<(), String>)>(done: F) {
		let p = RawPromise::new_rejected("oof".into())
			.then(|res| {
				let reason = match res {
					Ok(_) => {
						return reject_raw("new_rejected was resolved");
					},
					Err(v) => v,
				};
				if reason.as_str() != Some("oof") {
					return reject_raw(format!("new_rejected expected 'oof', got {}", js_to_string(reason)));
				}
				return stdweb::Value::Null;
			});
		test_raw_promise(p, done);
	}
	
	#[async_test]
	fn promise_new_resolved<F: FnOnce(Result<(), String>)>(done: F) {
		let p = Promise::<String, String>::new_resolved("hello world".into())
			.then(|res| {
				let value: String = match res {
					Ok(v) => v,
					Err(_) => {
						return Err(String::from("new_resolved was rejected"));
					}
				};
				if value.as_str() != "hello world" {
					return Err(format!("new_resolved expected 'hello world', got {:?}", value));
				}
				return Ok(PromiseOk::Immediate(()));
			});
		test_promise(p, done);
	}
	
	#[async_test]
	fn promise_new_rejected<F: FnOnce(Result<(), String>)>(done: F) {
		let p = Promise::<String, String>::new_rejected("oof".into())
			.then(|res| {
				let value: String = match res {
					Err(v) => v,
					Ok(_) => {
						return Err(String::from("new_rejected was resolved"));
					}
				};
				if value.as_str() != "oof" {
					return Err(format!("new_rejected expected 'oof', got {:?}", value));
				}
				return Ok(PromiseOk::Immediate(()));
			});
		test_promise(p, done);
	}
	
	fn http_req(url: &str) -> Promise<serde_json::Value,String> {
		let req = stdweb::web::XmlHttpRequest::new();
		req.open("GET", url).expect("open failed");
		
		let p = RawPromise::from_value(js!{
			return new Promise(function(resolve, reject) {
				let req = @{req.as_ref().clone()};
				req.addEventListener("load", resolve);
				req.addEventListener("abort", function() { reject("abort"); });
				req.addEventListener("error", function() { reject("error"); });
				req.addEventListener("timeout", function() { reject("timeout"); });
			});
		});
		req.send().unwrap();
		let p = p.then_to_typed::<serde_json::Value, String, _>(move |res| {
			let _ev = res.map_err(|v| v.into_string().unwrap())?;
			
			let body = req.response_text().unwrap().unwrap();
			let out = serde_json::from_str::<serde_json::Value>(&body).unwrap();
			return Ok(PromiseOk::Immediate(out));
		});
		
		return p;
	}
	
	#[async_test]
	fn ajax_request<F: FnOnce(Result<(), String>)>(done: F) {
		let p = http_req("https://httpbin.org/get")
			.and_then(|v| {
				let url_v = v.pointer("/url").ok_or(String::from("Expected url field in response"))?;
				let url = url_v.as_str().ok_or(String::from("url field in response was not a string"))?;
				if url == "https://httpbin.org/get" {
					return Ok(PromiseOk::Immediate(()));
				} else {
					return Err(format!("url field in response was incorrect, had value {:?}", url));
				}
			});
		test_promise(p, done);
	}
	
	#[async_test]
	fn return_a_promise<F: FnOnce(Result<(), String>)>(done: F) {
		let p = Promise::<String,String>::new_resolved(String::from("https://httpbin.org/get"))
			.and_then(|url| {
				console!(log, "url:", &url);
				return Ok(PromiseOk::Promise(http_req(&url)));
			})
			.and_then(|v| {
				let url_v = v.pointer("/url").ok_or(String::from("Expected url field in response"))?;
				let url = url_v.as_str().ok_or(String::from("url field in response was not a string"))?;
				if url == "https://httpbin.org/get" {
					return Ok(PromiseOk::Immediate(()));
				} else {
					return Err(format!("url field in response was incorrect, had value {:?}", url));
				}
			});
		test_promise(p, done);
	}
}