简体   繁体   English

如何处理返回Promise的函数

[英]How to handle function that returns a Promise

I'm wanting to declare a Promise's resolved value from a library like so. 我想从这样的库中声明Promise的可解析值。

// 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 等待不起作用,似乎我尝试过的所有操作均导致此错误: UnhandledPromiseRejectionWarning: Unhandled promise rejection

See below, as CertainPerformance mentioned in the comments, you can't use await at the top level yet. 参见下文,正如注释中提到的SomePerformance一样,您还不能在顶层使用await Additionally, in order to use await you must add the async keyword to the function in which you await the resolution of a Promise . 另外,为了使用await ,必须将async关键字添加到await 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);*/ } 您只需为promise构造function(resolve,reject){ /* your code here with resolve(value); and reject(error);*/ }提供一个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 function(resolve,reject){ /* your code here with resolve(value); and reject(error);*/ }作为参数,然后调用它并将x的值赋给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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM