【问题标题】:JS Promise <Pending> returnedJS 承诺 <Pending> 返回
【发布时间】:2018-06-06 17:35:43
【问题描述】:

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

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

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

我猜这主要是因为我对 Promise 不熟悉。

非常感谢任何帮助!

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));    

【问题讨论】:

  • 代码需要细化
  • 是的,当然quanitity 是一个承诺。您无法立即获得仅在将来创建的整数。只需在需要使用结果的地方使用 then 即可。

标签: javascript node.js shopify es6-promise


【解决方案1】:
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)) 

【讨论】:

  • 如何分配数量的结果。然后调用另一个对象属性?使用代码我得到的只是输出到控制台...我需要将其分配给另一个对象属性。
猜你喜欢
  • 2020-07-03
  • 2021-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-04
  • 1970-01-01
  • 2016-06-15
  • 1970-01-01
相关资源
最近更新 更多