首页 > 解决方案 > JS 承诺回来

问题描述

我目前正在努力从链式事件中返回一个值,从而导致 Promise 以挂起状态返回。

我的代码返回特定 Shopify 产品的元字段对象数组,然后我对其进行解析并希望返回一个整数值。

然而,当我调试我的代码时,我得到的只是一个处于挂起状态的承诺,而不是一个在使用范围内的已执行值。

我猜这主要是由于我对承诺的不熟悉。

非常感谢任何帮助!

var quantity = shopify.metafield.list({
  metafield: { owner_resource: 'product', owner_id: line_item.product_id }
}).then(metafields => new Promise(function(resolve, reject) { 

    //simplified code   
    resolve(2);
}))
.catch(error => console.log(error));    

标签: javascriptnode.jsshopifyes6-promise

解决方案


shopify.metafield.list({
  metafield: { owner_resource: 'product', owner_id: line_item.product_id }
}).then(metafields => new Promise(function(resolve, reject) { 

    //simplified code   
    resolve(2);
})).then((quantity)=> console.log(quantity))
.catch(error => console.log(error)); 

第二个 .then() 函数正在返回一个新的 promise,因此您需要再次链接 .then() 函数以获得从 promise(resolve) 返回的确切值

另一种方法是仅对包含第二个 .then() 函数返回的承诺的数量变量使用 .then() 函数

quantity.then((res)=> console.log(res)) 

推荐阅读