javascriptnode.jspromisepinata

Promise within a function


This code does not execute the promise of testAuthentication or pinFileToIPFS and i am curious if this is a node concept i am not familiar of.

function uploadToPinata(filename) {
    const pinata = pinataSDK(process.env.PINATA_KEY, process.env.PINATA_SECRET_KEY);
    pinata.testAuthentication().then((result) => {
        //handle successful authentication here
        console.log(result);
    }).catch((err) => {
        //handle error here
        console.log(err);
    });
    
    const readableStreamForFile = fs.createReadStream(filename);
    const options = {
        pinataMetadata: {
            name: "NYC_NFT_TESTING",
        },
        pinataOptions: {
            cidVersion: 0
        }
    };

    pinata.pinFileToIPFS(readableStreamForFile, options).then((result) => {
        //handle results here
        console.log(result);
    }).catch((err) => {
        //handle error here
        console.log(err);
    });
}

is there a problem with this code using a promise within a function? I attemped to make the function async but that did not help. This code works just fine outside of a function but not within one.


Solution

  • "does not execute the promise": this is a strange phrase. Promises are objects. They don't execute -- they are created. And your function really creates them. However, it does not do much when these promises are resolved.

    The problem is that uploadToPinata will execute all of the synchronous code and return. But then there are still a promises pending. Although you have console.log that will be executed once the relevant promise has resolved, there is no signal to the caller of uploadToPinata that these promises have resolved.

    It is probably easiest to use async and await:

    async function uploadToPinata(filename) {
        const pinata = pinataSDK(process.env.PINATA_KEY, process.env.PINATA_SECRET_KEY);
        const result = await pinata.testAuthentication();
        //handle successful authentication here
        console.log("authentication result", result);
        const readableStreamForFile = fs.createReadStream(filename);
        const options = {
            pinataMetadata: { name: "NYC_NFT_TESTING" },
            pinataOptions: { cidVersion: 0 }
        };
    
        const result2 = await pinata.pinFileToIPFS(readableStreamForFile, options);
        //handle results here
        console.log("pinFileToIPFS result", result2);
    }
    

    The caller of this function will now receive a promise, so it should probably want to do something when that promise has resolved:

    uploadToPinata(filename).then(() => {
        console.log("authentication and file operation done")
    }).catch(error => console.log("error", error));