简体   繁体   中英

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

I tried to pass data of readFile through Promise chain.

It is able to read but when I pass the read data to writeFile, it received undefined and that gets written to the file:

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. But I think you need to resolve with argData in readFromFileCallback.

You can read and write by using fs.Promises(from 10.0 available by default). 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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