简体   繁体   English

如何在 node.js 中沿 .then 链传递承诺数据?

[英]How to pass promise data down the .then chain in node.js?

I tried to pass data of readFile through Promise chain.我试图通过 Promise 链传递 readFile 的数据。

It is able to read but when I pass the read data to writeFile, it received undefined and that gets written to the file:它能够读取,但是当我将读取的数据传递给 writeFile 时,它​​收到未定义并写入文件:

Here is the output:这是输出:

node promise.js 
In fileFunction:
promiseResolveCallback():  File found!
readFromFileCallback: 11111111111111111111111111111111111111111111111111111111111111111111111111111111
11111111111111111111111111111111111111111111111111111111111111111111111111111111


writeToFileCallback: undefined

My code:我的代码:

var objFs   = require( 'fs' )

function promiseResolveCallback( arg )
{
    console.log("promiseResolveCallback(): ", arg)
}

function promiseRejectionCallback( arg )
{
    
    console.log("promiseRejectionCallback(): ", arg)
    throw -999;
}

function writeToFileCallback( argPromise )
{
    objFs.writeFile( 'new.js',
                     argPromise.data, 
                     ( argError ) => 
                     { 
                        if( argError ) 
                            throw argError 
                        else 
                            console.log( "writeToFileCallback: Written in new.js!" ) 
                     } 
                   )
}

function readFromFileCallback()
{
    return new Promise( (resolve, reject ) =>
                        {
                            objFs.readFile( 'new.js', ( argError, argData ) =>
                                                        {
                                                            if( argError )
                                                            {
                                                                reject( argError )
                                                                console.log( "readFromFileCallback: " + argError )
                                                            }
                                                            else
                                                            {
                                                                resolve( "read file \n")
                                                                console.log( "readFromFileCallback: " + argData )
                                                            }
                                                        }
                                          )
                        }
                     )  
}

function fileFunction()
{                        
     console.log("In fileFunction:")
     return new Promise( ( resolve, reject ) =>
                       {
                            objFs.open( 'new.js', 
                                        'r', 
                                        ( argError, argFD ) =>
                                        {
                                            if( argError )
                                            {
                                                reject( new Error("File not found!"), 1000);
                                            }
                                            else
                                            {
                                                resolve("File found!", 1000);
                                            }
                                        }
                                      )
                       }
                     );
} 

var objPromise = fileFunction()
objPromise.then( promiseResolveCallback, promiseRejectionCallback )
       .then( readFromFileCallback )
       .then( writeToFileCallback )

objPromise.catch( ( argError ) =>
                {
                    console.error( argError )
                } 
             )


                   
                    
                  

I'm quite new to this topic of Promises.我对 Promises 的这个话题很陌生。 But I think you need to resolve with argData in readFromFileCallback.但我认为您需要在 readFromFileCallback 中使用 argData 来解决。

You can read and write by using fs.Promises(from 10.0 available by default).您可以使用 fs.Promises(默认情况下从 10.0 开始)进行读写。 Example例子

const fs = require("fs");

async function writeInput(message) {
  try {
    await fs.promises.writeFile("new.txt", message, "utf8");
    console.log("well done");
  } catch (err) {
    console.log(err);
  }
}

writeInput("Put your args data here");

async function readInput() {
    const secret = await fs.promises.readFile("new.txt","utf8");
    console.log(secret);
  }
  
  readInput();

Output输出

well done
Put your args data here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM