鍍金池/ 問答/Linux  網(wǎng)絡安全  HTML/ co執(zhí)行generator函數(shù),如何在多個co函數(shù)都返回之后再返回數(shù)據(jù)?

co執(zhí)行generator函數(shù),如何在多個co函數(shù)都返回之后再返回數(shù)據(jù)?

let form = new multiparty.Form({
                encoding: 'utf-8',
                // uploadDir:"public/upload",  //文件上傳地址
                keepExtensions: true  //保留后綴
            })
            form.parse(ctx.req, function (err, fields, files) {
                let data=[]
                for(let f of files.file){
                    // 文件名
                    let date = new Date()
                    let time = '' + date.getFullYear() + (date.getMonth() + 1) + date.getDate()
                    let filepath = 'project/'+time + '/' + date.getTime()
                    let fileext = f.originalFilename.split('.').pop()
                    let upfile = f.path
                    let newfile = filepath + '.' + fileext
                    //ali-oss
                    co(function*() {
                        client.useBucket('p-adm-test')
                        let result = yield client.put(newfile, upfile)
                        console.log('文件上傳成功!', result.url)
                        data.push(result.url)
                        console.log(data)
                        resolve()
                    }).catch(function(err) {
                        console.log(err)
                    })
                }
                ctx.response.type = 'json'
                ctx.response.body = {
                    errno: 0,
                    data: data
                }
            })

如上代碼,我多次執(zhí)行了co函數(shù),希望每次執(zhí)行的時候返回的結果push到data數(shù)組里,最后返回到前端的數(shù)據(jù)是多次執(zhí)行之后的data,但是前端收到的只是第一次返回的data,如何解決?

回答
編輯回答
陌如玉

co返回的也是promise 按照你這種返回數(shù)組可以用promise.all

var fn = co.wrap(function*(newfile, upfile) {
  client.useBucket("p-adm-test");
  let result = yield client.put(newfile, upfile);
  return result.url;
});

1 . promise.all

var arr = []
for(let f of files.file){
    arr.push(fn(newfile,upfile))
}
//Promise.all(arr,function(res){
Promise.all(arr).then(function(res){
    ctx.response.body = {
        errno: 0,
        data: res
    }
})

2 . co嵌套


form.parse(ctx.req, co.warp(function* (err, fields, files) {
    let data = []
    for(let f of files.file){
        let res = yield fn(newfile,upfile)
        data.push(res)
    }
    ctx.response.body = {
        errno: 0,
        data: data
    }
}))
2018年6月21日 08:15