繁体   English   中英

如何处理返回Promise的函数

[英]How to handle function that returns a Promise

我想从这样的库中声明Promise的可解析值。

// lib.js
exports.foo = function(){
    return new Promise(..)
}

// main.js
import { foo } from "./lib"

let x = await foo()

等待不起作用,似乎我尝试过的所有操作均导致此错误: UnhandledPromiseRejectionWarning: Unhandled promise rejection

参见下文,正如注释中提到的SomePerformance一样,您还不能在顶层使用await 另外,为了使用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();
};

您只需为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);*/ }作为参数,然后调用它并将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