I'm wanting to declare a Promise's resolved value from a library like so.
// lib.js
exports.foo = function(){
return new Promise(..)
}
// main.js
import { foo } from "./lib"
let x = await foo()
The await isn't working, and it seems everything I've tried leads to this error: UnhandledPromiseRejectionWarning: Unhandled promise rejection
See below, as CertainPerformance mentioned in the comments, you can't use await
at the top level yet. Additionally, in order to use await
you must add the async
keyword to the function in which you await
the resolution of a Promise
.
// lib.js
exports.foo = function() {
return new Promise(..)
};
// main.js
import { foo } from "./lib";
function async main() {
let x = await foo();
};
You simply give the promise constructor a function(resolve,reject){ /* your code here with resolve(value); and reject(error);*/ }
function(resolve,reject){ /* your code here with resolve(value); and reject(error);*/ }
as a parameter then to call it and give the value to x
you call var x; foo().then(function(value){ x=value; } ); //here you can optionally add .catch(function(error){ your error catch imp here}); if you want to catch your error
var x; foo().then(function(value){ x=value; } ); //here you can optionally add .catch(function(error){ your error catch imp here}); if you want to catch your error
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.