承诺解决有什么问题? [英] What is wrong with promise resolving?

查看:22
本文介绍了承诺解决有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么想法吗?为什么节点说文件名未定义"?谢谢.合同、政策和发票功能无需数据即可解析,只需 resolve().

Any ideas? Why does node say 'filename is undefined'? Thanks. Contract, policy ans invoice functions resolve with no data, just resolve().

var dc = function(data) {

return new Promise(function(resolve, reject) {

    var filename = 'Test';

    var contract = function() { ... }

    var policy = function() { ... }

    var invoice = function() { ... }

    contract().then(invoice().then(policy().then(function() {
        console.log(filename); // Test
        resolve(filename); // UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): ReferenceError: filename is not defined
    })))
})

}

推荐答案

首先,你不能写:

contract().then(invoice() ... )

(如果 invoice() 函数返回 另一个 函数作为 then 处理程序,那将起作用)

(that would work if the invoice() function returned another function to act as a then handler)

你必须写:

contract().then(function (value) { invoice() ... })

或者:

contract().then(value => invoice() ... )

或者如果一个函数应该处理另一个函数的结果:

Or maybe this if one function should handle the result of other function:

contract().then(invoice).then(policy).then(function (result) { ... });

你必须作为参数传递给 then 的是一个函数,而不是调用函数的结果(在你的例子中这可能是一个承诺).

What you have to pass as an argument to then is a function, not a result of calling a function (which is probably a promise in your example).

我不知道这是否是您的方法的唯一问题,但这肯定是问题之一.当然它可能会起作用,但可能不是您期望的那样.

I don't know if that's the only problem with your approach but it is certainly one of the problems. Of course it may work but probably not how you expect.

如果您使用自 v7.0 起在 Node 中可用的 ES2017 async/await,则代替:

If you use ES2017 async/await that's available in Node since v7.0 then instead of:

contract().then(invoice).then(policy).then((result) => { ... });

你可以使用:

let a = await contract();
let b = await invoice(a);
let c = await policy(b);
// here your `result` is in `c`

甚至这个:

let result = await policy(await invoice(await contract()));

请注意,您只能在使用 async 关键字声明的函数中使用它.从版本 7 开始,这适用于 Node.对于旧版本的 Node,您可以使用基于生成器的协程使用略有不同语法的类似内容,或者您​​可以使用 Babel 来转换您的代码,如果这是您喜欢的,如果您已经这样做了做.

Note that you can only use it in functions declared with the async keyword. This works on Node since version 7. For older versions of Node you can use a similar thing with a slightly different syntax using generator-based coroutines, or you can use Babel to transpile your code if that's what you prefer of if that what you already do.

这是一个相当新的功能,但在 Stack Overflow 上有很多关于它的问题.见:

This is quite a new feature but there are a lot of questions on Stack Overflow about it. See:

这篇关于承诺解决有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆