这段代码怎么实现我想要的效果,异步有点懵了

// 循环同步任务
async function loopSyncTask() {
  await setInterval(() => {
    let authedStore = storage.getItem('authedStore') 
    log.info(
      '====================== sync message start ======================'
    )
    let syncResult = Object.keys(authedStore).map(async (key) => {
      let result = await syncMessage({
        host: authedStore[key].host,
        token: authedStore[key].token,
        userInfo: authedStore[key].storeName,
      })
      // 这里能打印到result
      return result  
    })
    log.info(JSON.stringify(syncResult))  //想要这里打印在中间,但是结果是[{},{}]
    log.info(
      '====================== sync message end   ======================'
    )
  }, 10000)
}

实际效果是这样的

======================= sync message start ======================
[{},{}]
====================== sync message end   ======================
阅读 1.3k
2 个回答

......你这明显就是错误的写法呀。
实际上代码执行到你的

log.info(JSON.stringify(syncResult))

异步代码并没有执行完。所以这里获取的是空。

建议优化语法

const requests = [];

Object.keys(authedStore).map(key => requests.push(syncShopeeMessage({
  host: authedStore[key].host,
 token: authedStore[key].token,
 userInfo: authedStore[key].storeName,
})))

let syncResult = await Promise.all(requests)

XDM哈哈我又自己解决啦

async function loopSyncTask() {
  await setInterval(async () => {
    let authedStore = storage.getItem('authedStore') 
    log.info(
      '====================== sync message start ======================'
    )
    let syncResult = await Promise.all(
      Object.keys(authedStore).map(async (key) => {
        let result = await syncShopeeMessage({
          host: authedStore[key].host,
          token: authedStore[key].token,
          userInfo: authedStore[key].storeName,
        })
        return result
      })
    )
    log.info('sync result:', JSON.stringify(syncResult))
    log.info(
      '====================== sync message end   ======================'
    )
  }, 10000)
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题