Javascript 承诺,嵌套函数 [英] Javascript promise, nested functions

查看:53
本文介绍了Javascript 承诺,嵌套函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是我正在运行 node.js,并且我有 2 个需要以特定顺序运行的函数,但是他们没有在此返回承诺.所以我想知道我将如何重写它以确保主函数会返回一个承诺,如果我有嵌套函数,我是否只运行第一个函数解析中的第二个函数?

my question is that im running node.js, and i have 2 functions that needs to be run in a specific order, however they are not returning a promise at this this. So i wonder how would i rewrite this to make sure that the main function would return a promise, and if i have nested functions, do i just run the 2nd function from the 1st functions resolve?

代码如下:

handleMd5Convert = (file) => {
  fs.readFile(file, (err, buf) => {
    fs.rename(file, directoryPath + md5(buf) + '.mp3', (err) => {
      if (err) console.log('ERROR: ' + err);
    })
  })
})

HandleMd5Convert 应该能够 .then()

HandleMd5Convert should be able to to .then()

/亚历克斯

推荐答案

您应该能够将整个事情包装在 new Promise() 中并使用 resolve()> &reject() 处理成功和错误:

You should be able to wrap the whole thing in a new Promise() and use resolve() & reject() to handle success and errors:

handleMd5Convert = (file) => {
  return new Promise((resolve, reject) => {
    fs.readFile(file, (err, buf) => {
      if (err) return reject(err)
      fs.rename(file, directoryPath + md5(buf) + '.mp3', (err) => {
        if (err) return reject(err);
        resolve()
      })
    })
  })
}

handleMd5Convert('test.txt')
.then(() => console.log("done"))
.catch(err => console.log("error:", err))

这篇关于Javascript 承诺,嵌套函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆