javascript - 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));
解决方案
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))
推荐阅读
- python - 仅当字符串与另一列匹配时,如何从一列添加?
- python - 为什么我无法访问 matplotlib 中的“ax”函数?
- python - 根据列表从熊猫系列中删除停用词
- python - 如何使用 OpenCV 中的指令“GaussianBlur()”演示 opencv GausssianBlurr 中使用的高斯内核?
- python - 使用模型的pickle对象来预测输出
- flutter - Flutter 使用 changeNotifier 不会改变小部件的外观
- jenkins - 没有为版本“apps/v1”注册任何类型的“部署” - 由 Jenkinsfile 构建
- git - GitHub 从其他存储库部署 git-pages 未按预期工作
- python - 尝试使用 Faker 填充 Django 应用程序数据库
- java - 有没有办法用数据和重写的 toString 方法创建一个匿名对象数组?