javascript - 我如何(有效地)链接我的 promise ,返回一个有值(value)的数组而不是 promise ?

标签 javascript promise es6-promise

我有一个找到数组的 promise 链。我希望数组返回一些结果(将来我可以将它设置为状态变量)。但是,我只是得到了 promise 。我想知道我在这里做错了什么。

现在,我在控制台记录数组中的项目,看看它是否返回值,而不是 Promise。

addIPFSItem = () => {

    var finalItems = []
    var searchAddress = "0x9Cf0dc46F259542A966032c01DD30B8D1c310e05";

    const contract = require('truffle-contract')
    const simpleStorage = contract(SimpleStorageContract)
    simpleStorage.setProvider(this.state.web3.currentProvider)

this.state.web3.eth.getAccounts((error, accounts) => {
  simpleStorage.deployed().then((instance) => {
    this.simpleStorageInstance = instance

    return this.simpleStorageInstance.getLength(searchAddress);
  }).then((accountLength) => {

    var movieItems = []
    var i;
    var indexCounter = 0;
    //WITHIN THIS LOOP extend the chain to add to movies
    for (i = 0; i < accountLength; i++) {

      var p = this.simpleStorageInstance.getBook(searchAddress, i, { from: searchAddress }).then((hashVal) => {
        return hashVal;
      }).then((hashVal)=>{
          var ipfsPrefix = "https://ipfs.io/ipfs/";
          var ipfsURL = ipfsPrefix + hashVal;
          return ipfsURL
      })

      var k = this.simpleStorageInstance.getTitle(searchAddress, i, { from: searchAddress }).then((title) => {
        return title;
      })

      var l = this.simpleStorageInstance.getContents(searchAddress, i, { from: searchAddress }).then((contents) => {
        return contents;
      })

      movieItems.push({id: i, poster_src: p, title: k, overview: l})
      indexCounter++
      console.log('counter: ', i, p, k, l)
    }

    //return items
    return movieItems
  }).then((array) =>{

    var i
    for(i=0; i<array.length; i++){
      console.log('Array item: ', array[i])
    }

    return finalItems
  })
})
}

我不知道在将 var p, var k, var l 添加到 时是否需要链接movieItems 数组。据推测,在我推送到 movieItems 之后,我可以尝试获取数组中的每个值,因为我已经检索到这些值了吗?

最佳答案

你在试图欺骗这里的 promise !

当你运行时

var l = this.simpleStorageInstance.getContents(searchAddress, i, { from: searchAddress }).then((contents) => {
  console.log('Retrieved contents');
  return contents;
});
movieItems.push({id: i, poster_src: p, title: k, overview: l});
console.log('Pushed!')

javascript 引擎会说“我将把这个 Promise 直接放入 l 并继续 movieItems.push”。如果你运行它,你会看到日志显示为

  • 插入!
  • 检索到的内容

关于 promises 有很多东西要学,所以我无法在这篇文章中解释所有内容。假设您有支持它的环境或构建工具,现在的快速修复方法是使用 async/await。这样你就可以让 javascript “等一下”,直到你的 promise 得到解决。

首先你改变 }).then((accountLength) => { to }).then(async (accountLength) => { 它告诉 javascript 你将要使用 await 并在函数内部使用 Promises。然后,您可以像这样使用 await 而不是使用 .then:

// Here I use `await` instead of `.then` to make the promise return "normally"
var hashVal = await this.simpleStorageInstance.getBook(searchAddress, i, { from: searchAddress });
// I do the transformations you did inside `.then(() => { ... })` "just" after the function call
var ipfsPrefix = "https://ipfs.io/ipfs/";
var ipfsURL = ipfsPrefix + hashVal;
var p = ipfsURL;

// Again, using `await` instead of `.then`
var k = await this.simpleStorageInstance.getTitle(searchAddress, i, { from: searchAddress })

var l = await this.simpleStorageInstance.getContents(searchAddress, i, { from: searchAddress });

这将使您的函数实际上返回一个值数组,而不是一个内部包含 promises 的数组。 希望这可以帮助! :)

关于javascript - 我如何(有效地)链接我的 promise ,返回一个有值(value)的数组而不是 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54079838/

相关文章:

javascript - 理解 Promise.all

javascript - 将简单函数直接传递给 es6 Promise.then

javascript - promise 没有正确捕获错误NodeJS

javascript - 通过 Google Scripts 从 Google Sheet 向 Telegram 发送消息

javascript - 用 promises 实现的 debounce 函数

javascript - promise 的顺序和并行处理

javascript - 我应该总是在可以使用 promise 的地方使用 Observables 吗?

javascript - 如何迭代二维数组中的 "box"

javascript - 如何使用 Angular 设置列高以包括整个窗口和所有内容?

javascript - 通过 JavaScript 进行部分回发期间阻止 UI